import network
import os
import machine
from machine import WDT
from machine import Pin
import time
from machine import Timer
import socket
import webrepl
#import webrepl_setup
webrepl.start()
os.listdir()
machine.freq(80000000)
p0 = Pin(0, Pin.OUT) 
p0.on()  
wdt = WDT()
cnt=0
orig_cnt=0
checkout_wifi_cnt = 0
tim = Timer(-1)
auto_feed_cnt= 0
def seton():
    global p0
    p0.off()     
    print("relay on")
def setoff():
    global p0
    global auto_feed_cnt
    p0.on()  
    auto_feed_cnt =0
    print("relay off")

def timer_func(t):
    global cnt
    global checkout_wifi_cnt
    global orig_cnt
    global auto_feed_cnt

    auto_feed_cnt += 1
    if auto_feed_cnt == 10000:
        seton()
    elif auto_feed_cnt == 10003:
        setoff()
        auto_feed_cnt =0

    wdt.feed()

    if orig_cnt<cnt:
        print("set envet")
        seton()
    if orig_cnt>0 and cnt==0:
        print("clear envet")
        setoff()
    orig_cnt=cnt
    
    if cnt >0 :
        cnt-=1
       # print(cnt)

    #checkout wifi 

            


tim.init(period=1000, mode=Timer.PERIODIC, callback=timer_func)

def check_wifi_connect():
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect('becky', 'beckybecky')
        while not sta_if.isconnected():
            print("...")
            break
    print("run end")
    print('network config:', sta_if.ifconfig())


def udp_server():   
    global cnt 
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 创建udp接收data数据  
    udp_socket.bind(("0.0.0.0", 8000)) #  绑定端口号  
    while True:
 #       wdt.feed()
        try:
            data,addr=udp_socket.recvfrom(1024)
            print('Received:',data,'From',addr)
            udp_socket.sendto(data,addr)#原样发回
            recv_data_str = data.decode("utf-8")
            print(recv_data_str)
            if recv_data_str == "on":
                print("on")
                seton()
            elif recv_data_str == "off":
                print("off")
                setoff()
            elif recv_data_str == "reset":
                machine.reset()
            else:
                data = int(recv_data_str)
                if data>0 and data<100:
                    cnt = data

            
        except Exception as ret:
            print("error:", ret)

def main():
    udp_server()


if __name__ == '__main__':
    time.sleep(4)
    seton()
    time.sleep(4)
    setoff()
    time.sleep(2)
    check_wifi_connect()
    main()
    
